package JDBC;

import JDBC.utils.GetConnectionUtils;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ReadClass {
    public static void main(String[] args) throws Exception {
        //获取连接
        Connection cnt = GetConnectionUtils.getConnection();

        String sql = """
                select * from music where id = 1;
                """;

        PreparedStatement preSta = cnt.prepareStatement(sql);

        ResultSet resultSet = preSta.executeQuery();
        Music music = null;
        String name = null;
        String singer = null;
        while (resultSet.next()) {
            InputStream isAudio = resultSet.getBlob("audio").getBinaryStream();
            InputStream isAlbum = resultSet.getBlob("album_cover").getBinaryStream();
            name = resultSet.getString("name");
            singer = resultSet.getString("singer");

            //byte[] audioData = new byte[isAudio.available()];
            //byte[] albumData = new byte[isAlbum.available()];
            music = new Music(name, singer, isAudio, isAlbum);
        }

        InputStream isAudio = music.getMusicIs();
        InputStream isAlbum = music.getAlbumIs();

        byte[] audioData = new byte[isAudio.available()];
        byte[] albumData = new byte[isAlbum.available()];

        isAudio.read(audioData);
        isAlbum.read(albumData);

        BufferedOutputStream bosAlbum = new BufferedOutputStream(new FileOutputStream("src/main/java/" + singer + "-" + name + ".jpg"));
        BufferedOutputStream bosAudio = new BufferedOutputStream(new FileOutputStream("src/main/java/" + singer + "-" + name + ".mp3"));

        bosAlbum.write(albumData);
        bosAudio.write(audioData);


    }
}
